package main

import (
	"fmt"
	"sort"
	"strconv"
)

//#link: https://leetcode-cn.com/problems/display-table-of-food-orders-in-a-restaurant/
func main() {
	orders := [][]string{
		{"David", "3", "Ceviche"}, {"Corina", "10", "Beef Burrito"}, {"David", "3", "Fried Chicken"},
		{"Carla", "5", "Water"}, {"Carla", "5", "Ceviche"}, {"Rous", "3", "Ceviche"},
	}
	fmt.Println(displayTable(orders))
}

//表中的数据行应该按餐桌桌号升序排列。餐按照字母顺序排
func displayTable(orders [][]string) [][]string {
	//map存所有食品
	allFood := make(map[string]bool)
	//map存第几桌对应的菜品数量
	tableNums := make(map[string]map[string]int)
	for _, order := range orders {
		allFood[order[2]] = true
		if value, ok := tableNums[order[1]]; ok {
			value[order[2]]++
			tableNums[order[1]] = value
		} else {
			tableNums[order[1]] = map[string]int{order[2]: 1}
		}
	}
	allFoodArray := make([]string, 0, len(allFood))
	for key := range allFood {
		allFoodArray = append(allFoodArray, key)
	}
	tableOrder := make([]int, 0)
	for key, _ := range tableNums {
		tableNum, _ := strconv.Atoi(key)
		tableOrder = append(tableOrder, tableNum)
	}

	//对菜进行排序
	sort.Slice(allFoodArray, func(i, j int) bool {
		return allFoodArray[i] < allFoodArray[j]
	})

	sort.Ints(tableOrder)

	result := make([][]string, len(tableOrder)+1)
	for i := 0; i <= len(tableOrder); i++ {
		result[i] = make([]string, len(allFoodArray)+1)
	}
	result[0][0] = "Table"
	for i, food := range allFoodArray {
		result[0][i+1] = food
	}

	for i := 1; i <= len(tableOrder); i++ {
		tableNumStr := strconv.Itoa(tableOrder[i-1])
		result[i][0] = tableNumStr
		tableInfo := tableNums[tableNumStr]
		for j := 1; j <= len(allFoodArray); j++ {
			if value, ok := tableInfo[result[0][j]]; ok {
				result[i][j] = strconv.Itoa(value)
			} else {
				result[i][j] = "0"
			}
		}
	}
	return result
}
